package model

import (
	"alarmservice/com"
	"time"
)

type IProjectIdContainer interface {
	GetProjectIds() []int64
}

type Project struct {
	Id         int64 `xorm:"pk autoincr" form:"-"`
	UserId     int64
	Title      string `valid:"Required;MaxSize(50);"`
	Apikey     string `form:"-"`
	Securekey  string `form:"-"`
	Desc       string `valid:"Required;MaxSize(200)"`
	Status     int
	CreateTime time.Time `xorm:"created" form:"-"`
}

type MapProject map[int64]*Project

func (mp MapProject) GetUserIds() []int64 {

	userIds := []int64{}
	for _, v := range mp {
		userIds = append(userIds, v.UserId)
	}

	return userIds
}

func (mp MapProject) GetProjectIds() []int64 {
	projectIds := []int64{}
	for _, v := range mp {
		projectIds = append(projectIds, v.Id)
	}

	return projectIds
}

func GetProjectFromProjectIdContainer(projectIdContainer IProjectIdContainer) (MapProject, error) {
	projectIds := projectIdContainer.GetProjectIds()
	projects := make(MapProject)

	if len(projectIds) <= 0 {
		return projects, nil
	}

	err := Orm.In("id", projectIds).Find(&projects)
	if err != nil {
		return nil, err
	}

	return projects, nil
}

func (p *Project) GenerateApiKey() {
	p.Apikey = string(com.RandomCreateBytes(32))
}

func (p *Project) GenerateSecureKey() {
	p.Securekey = string(com.RandomCreateBytes(32))
}

func NewProject() *Project {
	p := new(Project)
	p.Status = StatusNormal
	p.GenerateApiKey()
	p.GenerateSecureKey()
	p.CreateTime = time.Now()
	return p
}
